<template>
  <div class="vuex-view">
    <h1>This is vuex demo</h1>
    <p>全局store中的count: {{ count }}, getter double: {{ double_getter }}</p>
    <button @click="increment">increment count </button>
    <button @click="async_increment">async increment count in 2s</button>
    <p>setup中使用mapState辅助函数 name: {{ name }}, age: {{ age }}</p>
    <p>setup中使用mapGetters辅助函数 double: {{double}}</p>
    <button @click="changeName('wuwuwu')">mapMutations:changeName</button>
    <button @click="changeAge(25)">mapMutations:changeAge</button>
    <button @click="add">mapActions: async increment count in 2s</button>
  </div>
</template>

<script>
/**
 * @description vuex demo
 * useStore hooks 用来访问store
 * 辅助函数在setup中需要封装使用 mapState mapGetters返回的都是函数所以需要封装一下返回变量
 */
import { computed } from 'vue';
import { useStore, mapMutations,mapActions} from 'vuex';
import { useState, useGetter } from '@/utils/hooks'

export default {
  name: 'VuexView',
  setup() {
    const store = useStore();
    return {
      /**
       * 直接调用
       */
      count: computed(() => store.state.count), //state
      double_getter: computed(() => store.getters.double), // getters
      increment: () => store.commit('increment'), //mutations
      async_increment: () => store.dispatch('increment'), //actions
      /**
       * 使用辅助函数
       */
      ...useState(["name","age"]), //mapState
      ...useGetter(["double"]), //mapGetters
      ...mapMutations(["changeName","changeAge"]), //mapMutations
      ...mapActions({add: "increment"}) //mapActions
    }
  }
}
</script>